clear;
close all;
totalPlotCnt = 4;
fileName = '../doc/data/raw.png';
fileName = '../doc/data/badapple.jpg';

%% 展示原图+预处理
I=imread(fileName);%  提取图像
I=imresize(I, [256 256]);
subplot(1,totalPlotCnt,1), imshow(I);
title(fileName);
%% 提取边缘
I=rgb2gray(I);%将彩色图转换灰度图
BW1=edge(I,'sobel',0.075); %用SOBEL算子进行边缘检测
BW2=edge(I,'roberts');%用Roberts算子进行边缘检测
BW3=edge(I,'prewitt'); %用prewitt算子进行边缘检测
BW4=edge(I,'log'); %用log算子进行边缘检测
BW5=edge(I,'canny'); %用canny算子进行边缘检测
subplot(1,totalPlotCnt,2), imshow(BW1);
title('sobel edge check');
%% 边缘转换为无向图
BW = BW1;
picSize = size(BW);
xsize = picSize(1,1);
ysize = picSize(1,2);
serise = cast(zeros(512, 2), "uint8");
pixelIdx = 0;
for x = 1:xsize
    for y = 1:ysize
        if BW(x,y) == 1
            pixelIdx = pixelIdx +1;
            serise(pixelIdx, 1) = 255 - x;
            serise(pixelIdx, 2) = y;
        end
    end
end
subplot(1,totalPlotCnt,3), line(serise(:, 2), serise(:, 1));
ylim([1, 256]); xlim([1, 256]); 
daspect([1 1 1])
title({['line figure, fulldistance = ', num2str(Evaluation(serise))];[ num2str(length(serise(:,1))), ' pts']});
%% 最短路径
tic
trail = cast(zeros(length(serise(:,1)), 2), "uint8");
firstPt = serise(1,:);
serise(1,:) = [];
trail(1,:) = firstPt;
x = 1;
time = 0;
breakcnt = 0; fullcnt = 0;
while ~isempty(serise)
    nextPt = serise(1,:);
    distance = 2^16;
    src = cast(firstPt, "int32");
    routeSize = size(serise);
    for idx = 1:routeSize(1,1)
        pt = cast(serise(idx,:), "int32");
        ptDistance = sqrt(sum((src - pt).^2));
        if (ptDistance < distance)
            distance = ptDistance;
            nextPt = pt;
            minIdx = idx;
        end
        if (distance == 1)
            breakcnt = breakcnt + 1;
            break
        end
        fullcnt = fullcnt + 1;
    end
    serise(minIdx,:) = [];
    x = x + 1;
    trail(x,:) = nextPt;
    firstPt = nextPt;
end
timeCost = toc;
subplot(1,totalPlotCnt,4), line(trail(:, 2), trail(:, 1));
ylim([1, 256]); xlim([1, 256]); 
daspect([1 1 1])
title({['line figure, fulldistance = ', num2str(Evaluation(trail))];[ 'in ', num2str(timeCost * 1000), 'ms']});

%% 存csv文件
trailSize = length(trail(:,1));
outputCsv = cast(zeros(trailSize * 2, 1), "uint8");
for x = 1 : trailSize
    outputCsv(x * 2 - 1) = trail(x,2);
    outputCsv(x * 2) = trail(x,1);
end
csvwrite([fileName, '.csv'], outputCsv);


%% 全屏
set(gcf,'OuterPosition', [-6.2, 33.8, 2062.4, 1126.4]);

%% 应用至FPGA
exeName = 'start D:\10_PrjGieGie\PrjGieGieCppLoader\Debug\PrjGieGieCppLoader.exe ';
cmd = [exeName, fileName, '.csv'];
system(cmd);




